package v1

import (
	"backend/pkg/logging"
	"backend/pkg/upload"
	"fmt"
	"github.com/disintegration/imaging"
	"github.com/gin-gonic/gin"
	"os"
	"path"
	"strings"
)

func GetFile(c *gin.Context) {
	name := c.Param("name")
	size := c.Query("size")

	fullName := path.Join(upload.GetImagePath(), name)
	var height, width int
	switch size {
	case "":
		c.File(fullName)
		return
	case "small":
		width, height = 854, 480
		break
	case "medium":
		width, height = 1366, 768
		break
	case "large":
		width, height = 1920, 1080
		break
	case "phone":
		width, height = 320, 568
		break
	default:
		count, err := fmt.Sscanf(size, "%dx%d", &width, &height)
		if err != nil {
			logging.Warn(err)
			c.File(fullName)
			return
		}
		if count != 2 {
			logging.Warn("parsed fail.")
			c.File(fullName)
			return
		}
	}

	reader, err := os.Open(fullName)
	if err != nil {
		logging.Warn(err)
		c.File(fullName)
		return
	}
	fileSuffix := path.Ext(name)
	filenameOnly := strings.TrimSuffix(name, fileSuffix)
	tempImg := path.Join(upload.GetTempPath(), filenameOnly + ".jpeg")
	writer, err := os.Create(tempImg)
	if err != nil {
		logging.Warn(err)
		c.File(fullName)
		return
	}
	srcImage, err := imaging.Decode(reader)
	if err != nil {
		logging.Warn(err)
		c.File(fullName)
		return
	}
	dstImageFit := imaging.Fit(srcImage, height, width, imaging.Lanczos)
	err = imaging.Encode(writer, dstImageFit, imaging.JPEG)
	if err != nil {
		logging.Warn(err)
		c.File(fullName)
		return
	}
	c.File(tempImg)

	err = reader.Close()
	if err != nil {
		logging.Warn(err)
	}

	err = writer.Close()
	if err != nil {
		logging.Warn(err)
	}

	err = os.Remove(tempImg)
	if err != nil {
		logging.Warn(err)
	}
}
